/*
   Copyright (c) 2020 LinkedIn Corp.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package com.linkedin.data.codec.symbol;

/**
 * Extracts symbol table metadata.
 *
 * <p>These are meant ONLY for use by the {@link SymbolTableProvider} implementations that prefix server node uri and
 * a prefix to the symbol table name to implement a symmetric symbol table exchange protocol between Rest.li services.
 * Symbol table names generated by this class are encoded in the form of ServerNodeUri|SymbolTablePrefix-SymbolsHashCode
 * </p>
 */
public class SymbolTableMetadataExtractor
{
  protected static char SERVER_NODE_URI_PREFIX_TABLENAME_SEPARATOR = '|';

  /**
   * Extracts just the table name, and whether the table is local (aka served from the same instance) or not.
   *
   * @param fullName The full table name.
   *
   * @return A tuple containing the url prefix from where the table was served the table name, and if the table
   * is local or remote.
   */
  public SymbolTableMetadata extractMetadata(String fullName)
  {
    int index = fullName.indexOf(SERVER_NODE_URI_PREFIX_TABLENAME_SEPARATOR);

    // If no separator char was found, we assume it's a local table.
    if (index == -1)
    {
      return new SymbolTableMetadata(null, fullName, false);
    }

    if (index == 0 || index == fullName.length() - 1)
    {
      throw new RuntimeException("Unexpected name format for name: " + fullName);
    }

    String serverNodeUri = fullName.substring(0, index);
    String tableName = fullName.substring(index + 1);
    return createMetadata(serverNodeUri, tableName);
  }

  protected SymbolTableMetadata createMetadata(String serverNodeUri, String tableName)
  {
    // Assume all tables with a server node URI are remote.
    return new SymbolTableMetadata(serverNodeUri, tableName, true);
  }
}

